<template>
  <div class="banner-add">

    <div class="createPost-main-container">
      <el-form ref="form" label-width="120px" :rules="rules" :model="form">
        <div v-for="(item, idx) in basicItems" :key="idx">
          <el-card class="box-card logo-card">
            <div slot="header" class="clearfix">
              <span>序号：{{ idx + 1 }}</span>
              <el-button style="float: right; padding: 3px 0" type="text" @click="deletCard(idx)">删除</el-button>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                :disabled="idx === basicItems.length - 1"
                @click="moveDown(idx)"
              >下移</el-button>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                :disabled="idx === 0"
                @click="moveUp(idx)"
              >上移</el-button>
            </div>
            <div class="text item">
              <el-form-item v-if="item.valueType === 'image'" label="选择图片">
                <upload :data="item.imgData" />
              </el-form-item>
              <el-form-item v-else label="值">
                <el-input v-model="item.value" />
              </el-form-item>
              <el-form-item label="跳转类型" required>
                <el-select v-model="item.linkType" filterable placeholder="跳转类型">
                  <el-option
                    v-for="(type, index) in typeList"
                    :key="index"
                    :label="type.text"
                    :value="type.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item v-for="(type, _index) in activeTypeList(item.linkType)" :key="_index" label="跳转链接">
                <el-select v-model="item.link" filterable placeholder="跳转详情">
                  <el-option
                    v-for="(link, index) in links[type.ref]"
                    :key="index"
                    :label="link.name"
                    :value="link.id"
                  />
                </el-select>
              </el-form-item>
            </div>
          </el-card>
        </div>

        <el-button
          :loading="ajaxStatus"
          style="margin-left: 10px;"
          type="primary"
          plain
          @click="addCard"
        >
          增加
        </el-button>

      </el-form>
    </div>

    <sticky :class-name="'cms-sub-navbar '+ajaxStatus">
      <el-button :loading="ajaxStatus" style="margin-left: 10px;" type="success" @click="submitForm('up')">
        发布
      </el-button>
      <el-button :loading="ajaxStatus" @click="reset()">
        取消
      </el-button>
    </sticky>

    <el-dialog title="上传视频" :visible.sync="uploadVideo">
      <div style="line-height: 1; margin-bottom: 20px;">
        <el-alert
          title="请先上传视频封面图片"
          type="info"
          description="封面图片仅支持jpg/png格式，视频暂时仅支持mp4格式"
          show-icon
          :closable="false"
        />
      </div>
      <upload :data="videoImgData" />
      <div slot="footer" class="dialog-footer">
        <el-button :loading="uploading" @click="uploadVideo = false">取 消</el-button>
        <el-button
          :loading="uploading"
          type="primary"
          :disabled="!videoImgData.imgUrl"
          @click="uploadfile"
        >上传视频</el-button>
      </div>
    </el-dialog>

    <input
      :id="'videoIdx' + tabName"
      ref="inputer"
      type="file"
      name="file"
      style="display:none"
      @change="handleFileChange"
      @touchstart="handleFileChange"
    >

  </div>
</template>

<script>
import { getByCode, postData } from '@/api/basicConfig/index'
import Sticky from 'components/Sticky'
import Upload from 'components/Upload/img-upload'
import { uploadFile } from 'api/common'
import { getVocationalLink, getNewsTypeLink, getNewsLink, getBasicConfigLink, getContentConfigLink, getAlbumsLink } from '@/api/common'

const defaultForm = {
  classifyName: '首页轮播图',
  classifyCode: 'banner',
  basicItems: []
}

const typeList = [
  { value: 'news', text: '资讯', hasId: true, input: false, ref: 'newsLink' },
  { value: 'newsType', text: '类型', hasId: true, input: false, ref: 'newsTypeLink' },
  { value: 'albumConfig', text: '相册', hasId: true, input: false, ref: 'albumLink' },
  { value: 'sign', text: '报名链接', hasId: false },
  { value: 'noLink', text: '无链接', hasId: false }
]

export default {
  components: { Sticky, Upload },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    tabName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      ajaxStatus: false,
      form: Object.assign({}, defaultForm),

      uploadVideo: false,
      uploading: false,
      flagIdx: '',
      videoImgData: {
        myId: Math.random(),
        path: 'news',
        imgUrl: '',
        ImgSize: 10000,
        text: '视频封面图片大小不得超过300k'
      },
      typeList,
      basicItems: [{
        code: 'banner1',
        name: '首页轮播图1',
        value: '',
        valueType: 'image',
        link: '',
        linkType: '',
        imgData: {
          myId: Math.random(),
          path: 'category',
          imgUrl: '',
          ImgSize: 10000,
          text: '图片大小不得超过10000K，支持png/jpg格式'
        }
      }],
      links: {
        newsLink: [],
        newsTypeLink: [],
        basicConfigLink: [],
        vocationalLink: [],
        contentConfigLink: [],
        albumLink: []
      },
      videoForm: {
        file: null,
        path: 'home'
      },

      rules: {
      }
    }
  },
  computed: {
    activeTypeList() {
      return (value) => {
        return typeList.filter(type => type.value === value && type.hasId)
      }
    }
  },
  created() {
    this.fetchData('banner')
    this.getLinkData()
  },
  methods: {
    getLinkData() {
      getVocationalLink()
        .then(data => {
          this.links.vocationalLink = data.data.content
        })
      getNewsTypeLink()
        .then(data => {
          this.links.newsTypeLink = data.data
        })
      getNewsLink().then(data => {
        this.links.newsLink = data.data.content.map(item => {
          return {
            ...item,
            name: item.title
          }
        })
      })
      getBasicConfigLink().then(res => {
        const { data } = res
        this.links.basicConfigLink = data.map(item => {
          return {
            ...item,
            name: item.classifyName
          }
        })
      })
      getContentConfigLink().then(res => {
        const { data } = res
        this.links.contentConfigLink = data
      })
      getAlbumsLink().then(res => {
        const { data } = res
        this.links.albumLink = data
      })
    },
    addCard() {
      // const index = this.basicItems.length + 1
      this.basicItems.push({
        code: `banner${this.basicItems.length + 1}`,
        name: `轮播图${this.basicItems.length + 1}`,
        value: '',
        link: '',
        linkType: '',
        valueType: 'image',
        imgData: {
          myId: Math.random(),
          path: 'category',
          imgUrl: '',
          ImgSize: 10000,
          text: '图片大小不得超过10000K，支持png/jpg格式'
        }
      })
    },
    deletCard(idx) {
      this.basicItems.splice(idx, 1)
      if (this.basicItems) {
        for (let i = idx; i < this.basicItems.length; i++) {
          const basicItem = this.basicItems[i]
          basicItem.code = `banner${i + 1}`
          basicItem.name = `轮播图${i + 1}`
        }
      }
      console.log('banneris ', this.basicItems)
    },

    moveUp(index) {
      if (index < 1) {
        return
      }
      // 重制排序
      const upData = this.basicItems[index - 1]
      this.basicItems.splice(index - 1, 1)
      this.basicItems.splice(index, 0, upData)
    },

    // 下移
    moveDown(index) {
      // 重制排序
      const upData = this.basicItems[index + 1]
      this.basicItems.splice(index + 1, 1)
      this.basicItems.splice(index, 0, upData)
    },

    uploadVideoBtn(idx) {
      this.uploadVideo = true
      this.flagIdx = idx
    },

    addBuyLink(idx) {
      const item = {
        name: '',
        buyPlatformColor: '#000',
        link: ''
      }
      this.basicItems[idx].buyLink.push(item)
    },

    deleteBuyLink(idx, index) {
      this.basicItems[idx].buyLink.splice(index, 1)
    },

    // 上传文件 图片/视频
    handleFileChange() {
      if (this.uploading) {
        return
      }
      const inputDOM = this.$refs.inputer
      const file = inputDOM.files[0]
      // 判断是否是图片上传
      const imageType = /image.*/
      const isImage = file.type.match(imageType)
      this.checkImg(file, isImage).then(() => {
        this.uploading = true
        const formData = new window.FormData()
        Object.keys(this.videoForm).forEach((y) => {
          formData.append(y, this.videoForm[y])
        })
        formData.append('file', file)
        uploadFile(formData).then((re) => {
          this.uploading = false
          const { data } = re
          this.basicItems[this.flagIdx].value = data
          this.basicItems[this.flagIdx].videoUrl = data
          this.basicItems[this.flagIdx].videoContent = `<div>
                    <video
                      controls
                      x5-playsinline playsinline webkit-playsinline
                      poster="/${this.videoImgData.imgUrl}"
                      class="video_upload_con"
                      object-fit: fill" >
                        <source src="${data}" type="video/mp4" />
  		                  您的浏览器不支持video标签播放视频
                    </video>
                </div>`
          this.uploadVideo = false
          this.$refs.inputer.value = ''
          this.videoImgData.imgUrl = ''
        })
      })
    },

    // 获取上传图片宽高
    checkImg(file) {
      return new Promise((resolve, reject) => {
        if (file.type.includes('video')) {
          const isMP4 = file.type === 'video/mp4'
          if (!isMP4) {
            this.$alert('图片的格式暂时仅支持mp4格式哦～', '提示', {
              confirmButtonText: '确认',
              type: 'warning'
            })
            return
          }
          resolve({
            width: '',
            height: ''
          })
        } else {
          this.$alert('请上传正确格式的文件', '提示', {
            confirmButtonText: '确认',
            type: 'warning'
          })
          reject()
        }
      })
    },

    uploadfile() {
      window.document.getElementById(`videoIdx${this.tabName}`).click()
    },

    // 获取编辑数据
    fetchData(code) {
      getByCode(code).then(re => {
        const { data } = re
        this.form = Object.assign(this.form, data)
        const basicItems = JSON.parse(JSON.stringify(this.form.basicItems))
        basicItems.forEach(e => {
          e.imgData = {
            myId: Math.random(),
            path: 'category',
            imgUrl: e.value,
            ImgSize: 10000,
            text: '图片大小不得超过10000K，支持png/jpg格式'
          }
          e.videoContent = ''
        })
        this.basicItems = basicItems
      })
    },

    /**
       * 保存、发布接口
       *
       * id：保存为空，编辑传列表id
       */
    submitForm(status) {
      if (this.ajaxStatus) {
        return
      }
      this.ajaxStatus = true

      const errorText = this.validateForm()
      if (errorText) {
        this.ajaxStatus = false
        this.$message.error(errorText)
        return
      }
      this.form.basicItems = this.basicItems
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.status = status
          postData(this.form)
            .then(re => {
              this.ajaxStatus = false
              this.$notify({
                title: '成功',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.reset()
            })
            .catch(() => {
              this.ajaxStatus = false
            })
        } else {
          this.ajaxStatus = false
          this.$message.error('请正确填写完整信息后再发布')
          return false
        }
      })
    },

    resetActivityType(idx) {
      this.$set(this.basicItems[idx], 'detailLink', '')
      this.$set(this.basicItems[idx], 'buyLink', [{
        name: '',
        buyPlatformColor: '#000',
        link: ''
      }])
    },

    reset() {
      // 编辑发布后直接关闭tab跳转至列表页面
      this.fetchData('banner')
    },

    /**
       * 验证表单项
       * @returns {string} 错误提示
       */
    validateForm() {
      this.basicItems.forEach(item => {
        if (item.valueType === 'image') {
          item.value = item.imgData.imgUrl
        }
      })
      return ''
    }
  }
}
</script>
<style lang="scss">
  .href-remark{
    color: #5e6d82;
    .red {
      background-color: #fdf6ec;
      color: #e6a23c;
    }
  }
  .logo-card{
    margin-bottom: 10px;
  }
  .video_upload_con{
    height: 100px;
    width: auto;
  }
</style>

